﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using DAL;
using System.Text;

namespace PeisongWeb.admin
{
    public partial class orderList : adminPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (hasPermission("DB", 1))
                {
                    drpStatusBind();
                    rptBind();
                }
                else
                {
                    Library.Script.ClientMsgUrl("没有权限！", "index.aspx");
                    return;
                }

            }
        }

        #region Part I

        /// <summary>
        /// 列表中的订单状态
        /// </summary>
        private void drpStatusBind()
        {
            drp_Status.DataSource = logic.sysCode.orderStatus();
            drp_Status.DataBind();
            drp_Status.Items.Insert(0, new System.Web.UI.WebControls.ListItem("--请选择--", ""));
            drp_Status.Items.Remove(drp_Status.Items.FindByValue("6"));

            ddl_orderSource.DataSource = logic.sysCode.orderSource();
            ddl_orderSource.DataBind();
            ddl_orderSource.Items.Insert(0, new System.Web.UI.WebControls.ListItem("--请选择--", ""));
        }

        /// <summary>
        /// 详细信息中的订单状态
        /// </summary>
        private void drpBind()
        {
            ddl_Status.DataSource = logic.sysCode.orderStatus();
            ddl_Status.DataBind();
            ddl_Status.Items.Remove(ddl_Status.Items.FindByValue("6"));

            ddl_receiveTime.DataSource = logic.sysCode.receiveTime();
            ddl_receiveTime.DataBind();
        }

        void rptBind()
        {
            int customerId = logic.customer.userId;
            StringBuilder where = new StringBuilder();
            where.Append("1=1");
            if (txt_company.Text.Trim() != "")
                where.AppendFormat(" and company like '%{0}%'", txt_company.Text.Trim());
            if (txt_orderNo.Text.Trim() != "")
                where.AppendFormat(" and orderNo = '{0}'", txt_orderNo.Text.Trim());
            if (ext_StartInputDt.SelectedDate != DateTime.MinValue)
                where.AppendFormat(" and datediff(day,[orderDt],'{0}')<=0", ext_StartInputDt.Value.ToString());
            if (ext_EndInputDt.SelectedDate != DateTime.MinValue)
                where.AppendFormat(" and datediff(day,[orderDt],'{0}')>=0", ext_EndInputDt.Value.ToString());
            if (drp_Status.SelectedItem.Value != "")
                where.AppendFormat(" and [status] in ({0})", drp_Status.SelectedItem.Value);
            if (ddl_orderSource.SelectedItem.Value != "")
                where.AppendFormat(" and [source] in ({0})", ddl_orderSource.SelectedItem.Value);
            if (ext_startReceiveDt.SelectedDate != DateTime.MinValue)
                where.AppendFormat(" and datediff(day,[receiveDt],'{0}')<=0", ext_startReceiveDt.Value.ToString());
            if (ext_endReceiveDt.SelectedDate != DateTime.MinValue)
                where.AppendFormat(" and datediff(day,[receiveDt],'{0}')>=0", ext_endReceiveDt.Value.ToString());
            if (txt_ProName.Text.Trim() != "")
                where.AppendFormat(" and orderid IN (SELECT DISTINCT orderId FROM dbo.vw_OrderItem_list WHERE proName LIKE '%{0}%')", txt_ProName.Text.Trim());
            DataSet ds = logic.order.select(where.ToString(), "orderid desc", AspNetPager1.PageSize, AspNetPager1.CurrentPageIndex);
            //DataTable dt1 = ds.Tables[1];
            //for (int i = 0; i < dt1.Rows.Count; i++)
            //{
            //    if (logic.order.dymanicOrderUnsale(dt1.Rows[i]["orderNo"].ToString()) != 0)
            //        dt1.Rows[i]["orderNo"] = dt1.Rows[i]["orderNo"] + "缺货！";
            //}
            AspNetPager1.RecordCount = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
            rpt_list.DataSource = ds.Tables[1];
            rpt_list.DataBind();

            DataTable dt = logic.order.getTotal(where.ToString());
            lbl_orderTotal.Text = string.Format("{0:F2}", dt.Rows[0]["total"]);
        }

        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            rptBind();
        }

        protected void rpt_list_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType== ListItemType.Item || e.Item.ItemType== ListItemType.AlternatingItem)
            {
                Label s_lbl_OrderNo = e.Item.FindControl("s_lblOrderNo") as Label;
                Label s_lbl_Source = e.Item.FindControl("s_lblSource") as Label;
                Label s_lbl_Company = e.Item.FindControl("s_lblCompany") as Label;
                Label s_lbl_ReceiveDt = e.Item.FindControl("s_lblReceiveDt") as Label;
                Label s_lbl_OrderDt = e.Item.FindControl("s_lblOrderDt") as Label;

                DataRowView dv = e.Item.DataItem as DataRowView;
                int companyId = 0;
                if (dv!=null)
                {
                    int.TryParse(dv["companyId"].ToString(), out companyId);
                    DataRow dr = DAL.Order.listPreOrderInfo(companyId,dv["orderNo"].ToString());
                    //if (dr["a2"].ToString() == "1")
                    //{
                    //    s_lbl_OrderDt.Text = dr["a3"].ToString();
                    //    s_lbl_Source.ForeColor = System.Drawing.Color.Green;
                    //}
                    //if (dr["a1"].ToString() == "1")
                    //{
                    //    s_lbl_OrderNo.ForeColor = System.Drawing.Color.Red;
                    //}
                    //if (Convert.ToInt32(dr["a4"]) > 1 && DateTime.Parse(s_lbl_ReceiveDt.Text).ToString("yyyy-MM-dd") == DateTime.Now.AddDays(1).ToString("yyyy-MM-dd"))
                    //{
                    //    string cur_CompanyName = s_lbl_Company.Text;
                    //    s_lbl_Company.Text = string.Format("{0}({1})", cur_CompanyName, dr["a4"]);
                    //    s_lbl_Company.ForeColor = System.Drawing.Color.Green;
                    //}
                }
            }
        }

        protected void link_needFixOrder_search_Click(object sender, EventArgs e)
        {
            int customerId = logic.customer.userId;
            StringBuilder where = new StringBuilder();
            where.AppendFormat("1=1");
            where.Append(" and exists (select *from dynamicOrder a join dynamicOrderItem b on a.orderId=b.orderId where a.orderNo=dbo.vw_Order_list.orderNo and b.isOnSale=1)");

            if (txt_company.Text.Trim() != "")
                where.AppendFormat(" and company like '%{0}%'", txt_company.Text.Trim());
            if (txt_orderNo.Text.Trim() != "")
                where.AppendFormat(" and orderNo = '{0}'", txt_orderNo.Text.Trim());
            if (ext_StartInputDt.SelectedDate != DateTime.MinValue)
                where.AppendFormat(" and datediff(day,[orderDt],'{0}')<=0", ext_StartInputDt.Value.ToString());
            if (ext_EndInputDt.SelectedDate != DateTime.MinValue)
                where.AppendFormat(" and datediff(day,[orderDt],'{0}')>=0", ext_EndInputDt.Value.ToString());
            if (drp_Status.SelectedItem.Value != "")
                where.AppendFormat(" and [status] in ({0})", drp_Status.SelectedItem.Value);
            if (ddl_orderSource.SelectedItem.Value != "")
                where.AppendFormat(" and [source] in ({0})", ddl_orderSource.SelectedItem.Value);
            if (ext_startReceiveDt.SelectedDate != DateTime.MinValue)
                where.AppendFormat(" and datediff(day,[receiveDt],'{0}')<=0", ext_startReceiveDt.Value.ToString());
            if (ext_endReceiveDt.SelectedDate != DateTime.MinValue)
                where.AppendFormat(" and datediff(day,[receiveDt],'{0}')>=0", ext_endReceiveDt.Value.ToString());
            if (txt_ProName.Text.Trim() != "")
                where.AppendFormat(" and orderid IN (SELECT DISTINCT orderId FROM dbo.vw_OrderItem_list WHERE proName LIKE '%{0}%')", txt_ProName.Text.Trim());
            DataSet ds = logic.order.select(where.ToString(), "orderid desc", AspNetPager1.PageSize, AspNetPager1.CurrentPageIndex);
            AspNetPager1.RecordCount = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
            rpt_list.DataSource = ds.Tables[1];
            rpt_list.DataBind();

            DataTable dt = logic.order.getTotal(where.ToString());
            lbl_orderTotal.Text = string.Format("{0:F2}", dt.Rows[0]["total"]);
        }

        //订单列表中的搜索
        protected void btn_select_Click(object sender, EventArgs e)
        {
            rptBind();
        }

        //查看详细信息
        protected void rpt_list_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "details")
            {
                int id = Convert.ToInt32(e.CommandArgument);
                drpBind();
                getDetails(id);
                companyGroupBind();
                Repeater_OrderStatus.DataBind();
                OrderStatusBind(id);
            }
        }

        private void companyGroupBind()
        {
            int companyId = Convert.ToInt32(hd_companyid.Value);
            DataTable dt = CompanyGroup.listGroupByCompanyId(companyId);
            ddlCompanyGroup.DataSource = dt;
            ddlCompanyGroup.DataBind();

            if (dt.Rows.Count > 0)
            {
                lbl_company.Visible = false;
                ddlCompanyGroup.Visible = true;

                ListItem selectedItem = ddlCompanyGroup.Items.FindByValue(hd_companyid.Value);
                if (selectedItem != null)
                {
                    selectedItem.Selected = true;
                }
            }
            else
            {
                lbl_company.Visible = true;
                ddlCompanyGroup.Visible = false;
            }
        }

        private void getDetails(int orderid)
        {
            lit_bfp.Text = "";
            hd_orderid.Value = orderid.ToString();
            //DataSet ds = logic.order.select("orderid=" + orderid, "orderid", 1, 1);
            DataRow dr = logic.order.getDetailByOrderId(orderid);
            txtInvoiceCode.Text = dr["invoiceCode"].ToString();
            if (Convert.ToBoolean(dr["enabledWeeklyPrice"]))
                lit_bfp.Text = "<font color='red'>此单位为固定价格采购商</font>";
            hd_customerid.Value = dr["customerid"].ToString();
            string OrderNo = dr["orderNo"].ToString();
            lbl_OrderNo.Text = "订单编号：" + dr["orderNo"].ToString();

            if (dr["source"].ToString() == "1")         //订单来源为网站订单就显示用户名，电话订单就显示录入者
            {
                lbl_user.InnerText = "用户名：";
                lbl_username.Text = dr["username"].ToString();
            }
            else
            {
                lbl_user.InnerText = "录入者：";
                lbl_username.Text = logic.sysAdmin.getById(Convert.ToInt32(dr["customerid"])).Username;
            }
            lbl_orderSource.Text = dr["sourceName"].ToString();     // 订单来源：1、网站订单；2、电话订单
            lbl_orderDt.Text = dr["orderDt"].ToString();            // 下单日期
            //txt_fireightFee.Value = String.Format("{0:F2}", dr["fireightFee"]).ToString();
            ext_receiveDt.SelectedDate = Convert.ToDateTime(dr["receiveDt"]);        //收货日期
            //ddl_receiveTime.SelectedValue = Convert.ToDateTime(dr["receiveDt"]).Hour.ToString();    //收货时间
            //ext_receiveTime.Value = Convert.ToDateTime(dr["receiveDt"]).ToShortTimeString();

            string time = Convert.ToDateTime(dr["receiveDt"]).Hour - 1 + ":00" + "-" + Convert.ToDateTime(dr["receiveDt"]).ToShortTimeString();

            ListItem c = ddl_receiveTime.Items.FindByText(time);

            if (c != null)
            {
                ddl_receiveTime.ClearSelection();
                c.Selected = true;
            }

            //ddl_receiveTime.SelectedIndex = 


            //txt_taxfee.Value = String.Format("{0:F2}", dr["taxfee"]).ToString();
            lbl_Note.Text = dr["note"].ToString();          //订单中的客户备注
            txt_Amount.Value = String.Format("{0:F2}", dr["Amount"]).ToString();    //支付总价
            txt_serviceNote.Text = dr["serviceNote"].ToString();                    //客服备注
            lbl_StandardAmount.Text = String.Format("{0:F2}", dr["standardAmount"]).ToString(); //汇总总价(不算运费和税费)
            ddl_Status.SelectedValue = dr["status"].ToString();         //订单状态
            txt_closeReason.Text = dr["closeReason"].ToString();        //交易关闭原因
            lbl_company.Text = dr["company"].ToString();                //采购商公司名称
            lbl_contact.Text = dr["contact"].ToString();                //联系人
            lbl_contactMobile.Text = dr["contactMobile"].ToString();    //公司联系电话
            lbl_contactPhone.Text = dr["contactPhone"].ToString();          //联系人手机
            lbl_Address.Text = dr["areaName"].ToString() + dr["address"].ToString();    //收货地址
            hd_companyid.Value = dr["companyId"].ToString();                    //采购商ID
            hdCompanyNature.Value = logic.company.getById(int.Parse(dr["companyId"].ToString())).BusinessNature; //得到企业的性质>>>
            if (Convert.ToInt32(dr["status"]) == 4 || Convert.ToInt32(dr["status"]) == 5)   //如果订单是 交易成功 和 交易关闭 状态，就不能修改订单信息
            {
                btn_Save.Visible = lbn_Add.Visible = false;                     //修改订单 和 添加商品按钮 都隐藏
                btn_UpdateStatus.Visible = false;
            }
            else
            {
                btn_Save.Visible = lbn_Add.Visible = true;
                btn_UpdateStatus.Visible = true;
            }
            bind(orderid);
            bindUnsale(OrderNo);
            lbl_Total.Text = String.Format("{0:F2}", dr["standardAmount"]);     //订单细目中的汇总价格

            if (dr["status"].ToString() != "5")
            {
                a_print.HRef = "reportcustomerdetail.aspx?rb=&order=" + dr["orderNo"].ToString();
                a_print.Visible = true;
            }
            else
                a_print.Visible = false;

            if (dr["source"].ToString() == "4")
            {
                lbn_Add.Visible = false;
            }

            order_details.Show();
        }
        private void OrderStatusBind(int orderid)
        {
            DataTable dt = logic.orderStatusHistory.OrderStatuslist(orderid);
            if (dt.Rows.Count != 0)
            {
                Repeater_OrderStatus.DataSource = dt;
                Repeater_OrderStatus.DataBind();
            }
        }

        #endregion 

        #region Part II

        //修改订单信息和订单细目中的商品数量
        protected void btn_Save_Click(object sender, EventArgs e)
        {
            int orderid = Convert.ToInt32(hd_orderid.Value);
            OrderEntity orderEnt = logic.order.getById(orderid);
            //如果是固定价格采购商的订单，判断收货日期
            if (logic.company.getById(orderEnt.CompanyId).EnabledWeeklyPrice)
            {
                //订单中的收货日期是否正确（不能超过当前周期，如果超过当前周期则商品价格不一样，需要重下订单！）
                if (!logic.buyerFixedPricePeriod.isValidReceiveDt(orderid, ext_receiveDt.SelectedDate))
                {
                    Library.Script.ClientMsg("对不起，收货日期不在当前周期内，请重新选择！");
                    return;
                }
            }

            if (ddl_Status.SelectedValue == "4" || ddl_Status.SelectedValue == "3")
            {
                if (logic.orderItem.isNotquoted(orderid))
                {
                    Library.Script.ClientMsg("对不起，该订单中有时价商品还未报价，不能提交订单！");
                    return;
                }
            }

            OrderEntity _order = new OrderEntity();

            if (!string.IsNullOrEmpty(ddlCompanyGroup.SelectedValue))
            {
                _order.CompanyId = Convert.ToInt32(ddlCompanyGroup.SelectedValue);
            }
            else
            {
                _order.CompanyId = Convert.ToInt32(hd_companyid.Value);
            }

            _order.Orderid = orderid;
            decimal standardAmount = 0m;
            decimal.TryParse(lbl_StandardAmount.Text,out standardAmount);
            _order.StandardAmount = Math.Round(standardAmount,2, MidpointRounding.AwayFromZero);     //汇总总价
            //_order.Amount = Convert.ToDecimal(txt_Amount.Value);          //支付总价暂为不可修改
            _order.Amount = standardAmount;
            _order.FireightFee = 0;
            _order.Taxfee =0;
            _order.Status = ddl_Status.SelectedValue;                //订单状态
            _order.ServiceNote = txt_serviceNote.Text;               //客服备注
            //_order.ReceiveDt = Convert.ToDateTime(ext_receiveDt.Value).AddHours(Convert.ToInt32(ddl_receiveTime.SelectedValue));    //收货时间
            string timeRange = ddl_receiveTime.SelectedItem.Text;
            int hour = Convert.ToInt32(timeRange.Substring(timeRange.IndexOf("-") + 1, timeRange.Length - (timeRange.IndexOf("-") + 4)));
            _order.ReceiveDt = Convert.ToDateTime(ext_receiveDt.Value).AddHours(hour);    //收货时间

            _order.CloseReason = txt_closeReason.Text;              //交易关闭
            _order.AdminId = logic.sysAdmin.AdminID;                 //操作者ID

            for (int i = 0; i < rpt_OrderItems.Items.Count; i++)    //修改商品细目表
            {
                RepeaterItem row = rpt_OrderItems.Items[i];
                HiddenField hid = row.FindControl("hid_oiId") as HiddenField;
                TextBox txt = row.FindControl("txtQuantity") as TextBox;
                TextBox txtNote = row.FindControl("txtCustomerNote") as TextBox;
               
                int oiid = Convert.ToInt32(hid.Value);
                decimal quantity = Convert.ToDecimal(txt.Text);
                logic.orderItem.updateQuantity(oiid, quantity, txtNote.Text);      //根据细目ID 和 商品数量 修改
            }

            OrderStatusHistoryEntity _Ostatus = new OrderStatusHistoryEntity();
            _Ostatus.OrderId = orderid;
            _Ostatus.Status = _order.Status;
            _Ostatus.AdminId = _order.AdminId;
            _Ostatus.Remarks = txt_closeReason.Text.Trim();
            _Ostatus.ReceivDt = _order.ReceiveDt;
            _Ostatus.Note = _order.ServiceNote;
            logic.orderStatusHistory.OrderStatusHistoryInsert(_Ostatus, true);


            logic.order.update(_order);
            Library.Script.ClientMsg("修改成功！");
            rptBind();
            //getDetails(orderid);
        }

        //删除商品
        protected void rpt_OrderItems_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "Del")
            { 
                int oiid = Convert.ToInt32(e.CommandArgument);

                // 保存数据到历史订单细目表
                logic.orderItemHistory.insert(oiid, logic.sysAdmin.AdminID);

                logic.orderItem.delete(oiid);
                Library.Script.ClientMsg("删除成功！");
                int orderid = Convert.ToInt32(hd_orderid.Value);
                getDetails(orderid);
            }
            if (e.CommandName == "Deduct")
            {
                int oiid = Convert.ToInt32(e.CommandArgument);
                hd_oiid.Value = oiid.ToString();
                ddl_deductType.DataSource = logic.sysCode.deductType();
                ddl_deductType.DataBind();
                lbl_deductRatio.Text = Convert.ToInt32(logic.webset.list().DeductRatio*100)+"%";
                lbl_productName.Text = "商品名称："+logic.orderItem.select("oiid=" + oiid, "oiid", 1, 1).Tables[1].Rows[0]["proName"].ToString();
                win_Deduct.Show();
            }
        }

        /// <summary>
        /// 绑定所选择的订单下的商品信息
        /// </summary>
        /// <param name="orderid"></param>
        void bind(int orderid)
        {
            rpt_OrderItems.DataSource = logic.orderItem.select("orderId=" + orderid, "categoryId", 100, 1).Tables[1];
            rpt_OrderItems.DataBind();
        }

        void bindUnsale(string orderno)
        {
            DataTable dt = logic.orderItem.selectUnsale("orderNo=" + orderno, "productId", 100, 1).Tables[1];
            if (dt.Rows.Count > 0)
            {
                panel_needFixProduct.Visible = true;
                rpt_UnSale_list.DataSource = dt;
                rpt_UnSale_list.DataBind();
            }
            else
            {
                panel_needFixProduct.Visible = false;
            }
        }

        //显示所有商品信息
        protected void lbn_Add_Click(object sender, EventArgs e)
        {
            int companyId = Convert.ToInt32(hd_companyid.Value);
            CompanyEntity companyEntity = logic.company.getById(companyId);

            if (companyEntity.EnabledWeeklyPrice)
            {
                DateTime receiveDt = logic.order.getById(Convert.ToInt32(hd_orderid.Value)).ReceiveDt;
                //DateTime receiveDt = ext_receiveDt.SelectedDate;
                DataTable dt = logic.buyerFixedPricePeriodItem.listByBuyerIdAndReceiveDt(companyId, receiveDt);
                if (dt.Rows.Count!=0)
                {
                    rpt_WeeklyProducts.DataSource = dt;
                    rpt_WeeklyProducts.DataBind();
                    weeklyProduct_add.Show();
                    lit_bfpTitle.Text = lbl_company.Text.Trim() + "<font color='red'>" + receiveDt.ToShortDateString() + "</font>" + "  配送的商品价格如下：";
                }
            }
            else
            {
                categoryRootBind();
                categorySubBind();
                rptProBind();
            }
            //categoryRootBind();
            //categorySubBind();
            //rptProBind();
        }

        //订单详细信息中的搜索
        protected void lbn_search_Click(object sender, EventArgs e)
        {
            AspNetPager2.CurrentPageIndex = 1;
            rptProBind();
        }

        //绑定在采购商的采购范围中的商品
        void rptProBind()
        {
            int companyId = Convert.ToInt32(hd_companyid.Value);
            StringBuilder where = new StringBuilder();
            //where.Append("categoryIsShow=1");
            where.Append("companyId = " + companyId + " and categoryIsShow=1");
            if (ddl_CategoryRoot.SelectedValue != "")
                where.AppendFormat(" and newCategoryId={0}", ddl_CategoryRoot.SelectedValue);
            if (ddl_CategorySub.SelectedValue != "")
                where.AppendFormat(" and categoryId={0}", ddl_CategorySub.SelectedValue);
            if (txt_ProductNo.Text.Trim() != "")
                where.AppendFormat(" and productNo like '%{0}%'", txt_ProductNo.Text.Trim());
            if (txt_ProductName.Text.Trim() != "")
                where.AppendFormat(" and [Name] like '%{0}%'", txt_ProductName.Text.Trim());

            //DataSet ds = logic.buyerRange.listWithPrice(where.ToString(), "productId", AspNetPager2.PageSize, AspNetPager2.CurrentPageIndex);
            //DataSet ds = logic.product.listWithCurrentPrice(Convert.ToInt32(hd_companyid.Value),
                //where.ToString(), "productId", AspNetPager2.PageSize, AspNetPager2.CurrentPageIndex);
            DataSet ds = logic.product.listWithCurrentPriceAdmin(where.ToString(), "productId", AspNetPager2.PageSize, AspNetPager2.CurrentPageIndex);
            AspNetPager2.RecordCount = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
            rpt_Products.DataSource = ds.Tables[1];
            rpt_Products.DataBind();
            product_add.Show();
        }

        protected void AspNetPager2_PageChanged(object sender, EventArgs e)
        {
            rptProBind();
        }

        /// <summary>
        /// 根据采购商的采购范围绑定大类
        /// </summary>
        void categoryRootBind()
        {
            int companyId = Convert.ToInt32(hd_companyid.Value);
            //ddl_CategoryRoot.DataSource = logic.category.listWithCompanyRange(companyId);
            //ddl_CategoryRoot.DataSource = logic.buyerRange.rootCategorylistWithCompanyRange(companyId);
            ddl_CategoryRoot.DataSource = logic.category.getByParent(0);
            ddl_CategoryRoot.DataBind();
            ddl_CategoryRoot.Items.Insert(0,new ListItem("-所有大类-",""));
        }

        /// <summary>
        /// 根据大类得到小类
        /// </summary>
        void categorySubBind()
        {
            if (ddl_CategoryRoot.SelectedValue!="")
            {
                int companyId = Convert.ToInt32(hd_companyid.Value);
                //DataTable dt = logic.category.getByParent(Convert.ToInt32(ddl_CategoryRoot.SelectedValue));
                //DataTable dt = logic.buyerRange.subCategory_listWithCompanyRange(companyId, Convert.ToInt32(ddl_CategoryRoot.SelectedValue));
                DataTable dt = logic.category.getByParent(Convert.ToInt32(ddl_CategoryRoot.SelectedValue));
                ddl_CategorySub.DataSource = dt;
                ddl_CategorySub.DataBind();
                ddl_CategorySub.Items.Insert(0, new ListItem("-请选择小类-", "")); 
            }
        }

        protected void ddl_CategoryRoot_SelectedIndexChanged(object sender, EventArgs e)
        {
            categorySubBind();
        }

        //添加商品
        protected void lbn_AddOrderItem_Click(object sender, EventArgs e)
        {
            foreach (RepeaterItem row in rpt_Products.Items)
            {
                if (row.ItemType == ListItemType.AlternatingItem || row.ItemType == ListItemType.Item)
                {
                    CheckBox cbxUser = row.FindControl("cbx_isUser") as CheckBox;
                    TextBox txtQuantity = row.FindControl("txtQuantity") as TextBox;
                    TextBox txtnote = row.FindControl("txtNote") as TextBox;
                    
                    if (cbxUser.Checked)
                    {
                        OrderItemEntity oi = new OrderItemEntity();
                        oi.CustomerId = Convert.ToInt32(hd_customerid.Value);
                        oi.Note = txtnote.Text;
                        oi.OrderId = Convert.ToInt32(hd_orderid.Value);
                        oi.Price = Convert.ToDecimal(cbxUser.Attributes["price"]);
                        oi.ProductId = Convert.ToInt32(cbxUser.Attributes["productId"]);
                        oi.Quantity = Convert.ToDecimal(txtQuantity.Text);
                        oi.InitQuantity = oi.Quantity;
                        oi.BusinessNature = cbxUser.Attributes["businessNature"];
                        PriceEntity pr = logic.price.getByProduct(oi.ProductId, oi.BusinessNature);
                        oi.SellerId = pr.CompanyId;
                        oi.SellerPrice = pr.SellerPrice;
                        oi.Unit = pr.Unit;
                        logic.orderItem.update(oi);
                    }
                }
            }

            int orderid = Convert.ToInt32(hd_orderid.Value);
            rptBind();
            getDetails(orderid);
        }

        // 固定报价商品添加
        protected void lbn_AddWeeklyOrderItem_Click(object sender,EventArgs e)
        {
            TextBox txtNote = null;
            TextBox txtQuantity = null;
            HiddenField hid_bpid = null;
            Label lbl_price = null;
            Label lbl_unit = null;

            foreach (RepeaterItem item in rpt_WeeklyProducts.Items)
            {
                if (item.ItemType== ListItemType.AlternatingItem || item.ItemType== ListItemType.Item)
                {
                    CheckBox chk = item.FindControl("cbx_isSelect") as CheckBox;
                    if (chk!=null && chk.Checked)
                    {
                        txtNote = item.FindControl("txtNote") as TextBox;
                        txtQuantity = item.FindControl("txtQuantity") as TextBox;
                        hid_bpid = item.FindControl("hid_bpid") as HiddenField;
                        lbl_price = item.FindControl("lbl_price") as Label;
                        lbl_unit = item.FindControl("lbl_unit") as Label;

                        OrderItemEntity oi = new OrderItemEntity();
                        oi.CustomerId = Convert.ToInt32(hd_customerid.Value);
                        oi.Note = txtNote.Text;
                        oi.OrderId = Convert.ToInt32(hd_orderid.Value);
                        oi.Price = Convert.ToDecimal(lbl_price.Text);
                        oi.Quantity = Convert.ToDecimal(txtQuantity.Text);
                        oi.InitQuantity = oi.Quantity;
                        oi.BusinessNature = chk.Attributes["businessNature"];

                        BuyerFixedPricePeriodItemEntity bfpEnt = logic.buyerFixedPricePeriodItem.getBybpId(Convert.ToInt32(hid_bpid.Value));
                        oi.ProductId = bfpEnt.ProductId;
                        oi.SellerId = bfpEnt.SellerId;
                        oi.SellerPrice = bfpEnt.SellerPrice;
                        oi.Unit = lbl_unit.Text.Trim();
                        logic.orderItem.update(oi);
                    }
                }
            }

            int orderid = Convert.ToInt32(hd_orderid.Value);
            rptBind();
            getDetails(orderid);
        }

        protected void lbl_cancel_Click(object sender, EventArgs e)
        {
            int orderid = Convert.ToInt32(hd_orderid.Value);
            product_add.Close();
            getDetails(orderid);
        }

        protected void lbtn_Search_Click(object sender, EventArgs e)
        {
            rptBind();
        }

        protected void btn_UpdateStatus_Click(object sender, EventArgs e)
        {
            int orderid = Convert.ToInt32(hd_orderid.Value);
            if (ddl_Status.SelectedValue == "4" || ddl_Status.SelectedValue=="3")
            {
                if (logic.orderItem.isNotquoted(orderid))
                {
                    Library.Script.ClientMsg("对不起，该订单中有时价商品还未报价，不能提交订单！");
                    return;
                }
            }
            OrderEntity _order = new OrderEntity();
            _order.Orderid = orderid;
            _order.Status = ddl_Status.SelectedValue;
            _order.AdminId = logic.sysAdmin.AdminID;
            
            OrderStatusHistoryEntity _Ostatus = new OrderStatusHistoryEntity();
            _Ostatus.OrderId = orderid;
            _Ostatus.Status = _order.Status;
            _Ostatus.AdminId = _order.AdminId;
            _Ostatus.Remarks = txt_closeReason.Text.Trim();
            _Ostatus.ReceivDt =DateTime.Now;
            _Ostatus.Note = txt_serviceNote.Text;
            logic.orderStatusHistory.OrderStatusHistoryInsert(_Ostatus, false);

            logic.order.updateStatus(_order);
            Library.Script.ClientMsg("修改状态成功！");
            rptBind();
        }

        [Coolite.Ext.Web.AjaxMethod]
        public string orderList_getDetails(int productid)
        {
            DataTable dt = logic.files.getListByProduct(productid);
                //img_product.Src = Library.Resource.UploadPath + Library.Resource.FileThumbnail1 + "/" + dt.Rows[0]["systemName"].ToString();
            return Library.Resource.UploadPath + Library.Resource.FileThumbnail1 + "/" + dt.Rows[0]["systemName"].ToString();
            
        }

        protected void btn_deduct_Click(object sender, EventArgs e)
        {
            int oiid = Convert.ToInt32(hd_oiid.Value);
            string type = ddl_deductType.SelectedValue;
            string reson = txt_reason.Text.Trim();
            int adminId= logic.sysAdmin.AdminID;
            logic.deductMoney.insert(oiid,type,reson,adminId);
            Library.Script.ClientMsg("操作成功！");
            rptBind();
        }

        #endregion


       
    }
}
